package ink.ykb.demo.config;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisCacheManagerCustomizer {
  
  /**
   * 缓存默认存活时间
   */
  @Value("${spring.cache.redis.time-to-live}")
  private Long cacheTimeToLive;

  
  @Bean
  public RedisCacheManager getRedisCacheManager(RedisConnectionFactory redisConnectionFactory){
	  //初始化一个RedisCacheWriter
      RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
      //设置CacheManager的值序列化方式为json序列化
      RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
      RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                                                  .fromSerializer(jsonSerializer);
      RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
                                                  .serializeValuesWith(pair);
      //设置默认超过期时间
      defaultCacheConfig.entryTtl(Duration.ofSeconds(cacheTimeToLive));
      //初始化RedisCacheManager
      return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);

  }


}
